package org.luxor.commons.openfeign.component;

import com.fasterxml.jackson.databind.JsonNode;
import feign.Response;
import feign.RetryableException;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.luxor.commons.core.exception.FeignCallException;
import org.luxor.commons.core.utils.Jackson2Utils;

/**
 * feign异常处理
 *
 * @author Mr.Yan
 **/
public class FeignErrorDecoder extends ErrorDecoder.Default {

    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = super.decode(methodKey, response);
        // 如果是RetryableException，则返回继续重试
        if (exception instanceof RetryableException) {
            return exception;
        }
        try {
            String errorContent = Util.toString(response.body().asReader());
            JsonNode result = Jackson2Utils.toJsonObject(errorContent);
            Integer code = result.path("code").asInt();
            String message = result.path("message").asText();
            return new FeignCallException(String.format("(%s)%s", code, message));
        } catch (Exception e) {
            return new FeignCallException(e);
        }
    }

}
